package sortStream;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamSortExample02 {
    static class Person {
        String name;
        int age;

        Person(String name, int age) {
            this.name = name;
            this.age = age;
        }

        int getAge() {
            return age;
        }

        public String getName() {
            return name;
        }

        @Override
        public String toString() {
            return name + ": " + age;
        }
    }

    public static void main(String[] args) {
        List<Person> people = Arrays.asList(
                new Person("Alice", 22),
                new Person("Charlie", 30),
                new Person("David", 25),
                new Person("Bob", 20)
        );

        // Sorting people by age using Stream
        List<Person> sortedByAge = people.stream()
                //自然排序
                .sorted((p1, p2) -> Integer.compare(p1.getAge(), p2.getAge()))
                .collect(Collectors.toList());

        // Displaying the sorted list
        sortedByAge.forEach(System.out::println);
        System.out.println("------------------自定义排序--------------");
        //先根据年龄再根据姓名排序
        List<Person> collect = people.stream().sorted((p1, p2) -> {
            if (p1.getAge() == p2.getAge()) {
                return p1.getName().compareTo(p2.getName());
            } else {
                return p2.getAge() - p1.getAge();
            }

        }).collect(Collectors.toList());
        collect.forEach(System.out::println);
    }
}
